package lib

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func CheckRepo(repoPath, service string) (err error) {
	if !strings.HasSuffix(repoPath, ".git") {
		repoPath = fmt.Sprintf("%s.git", repoPath)
	}

	fileInfo, fileErr := os.Stat(repoPath)

	if fileErr != nil {
		// TODO: fileErr may be a permission error or other
		// init repo if not exists only for receive-pack
		if service == "git-receive-pack" {
			initCmd := exec.Command("git", "init", "--bare", repoPath)
			samplePostHook := fmt.Sprintf("%s/hooks/post-update.sample", repoPath)
			PostHook := fmt.Sprintf("%s/hooks/post-update", repoPath)
			activePostHook := exec.Command("cp", samplePostHook, PostHook)
			if err = os.Mkdir(repoPath, 0755); err != nil {
				return err
			}
			if err = initCmd.Run(); err != nil {
				return err
			}
			err = activePostHook.Run()
		} else {
			err = fileErr
		}
	} else if fileInfo.IsDir() {
		// TODO: check if dir is a valid bare repo
		err = nil
	} else if fileInfo.Mode().IsRegular() {
		err = errors.New("Not a valid repository")
	}
	return err
}
